package a09threadsafe1;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86131
 * Date: 2024-04-17
 * Time: 10:47
 */
public class MyThread extends Thread{

    //表示这个类的所有对象,都共享tickets数据
    static int ticket = 0;

    //锁对象,一定是要为唯一的
    static Object obj = new Object();

    @Override
    public void run() {
        while(true) {
            synchronized (obj){  //括号内添加锁对象 也可 以填 (MyThread.class)
                //同步代码块
                if(ticket < 100) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    ticket++;
                    System.out.println(getName()+"正在卖"+ticket+"张票!!!");
                }else{
                    break;
                }
            }
        }
    }
}
